package cn.fl.framework.listener;

import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.cmm.base.framework.utils.ThreadPoolUtils;
import cn.cmm.cache.framework.utils.PropertiesCacheUtils;
import com.lionbridge.activiti.util.redis.RedisUtils;
import com.lionbridge.log.ext.LogUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisSentinelPool;
import redis.clients.jedis.Protocol;
import redis.clients.util.Pool;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 监听程序启动和停止,可以做一些简单的启停业务操作
 * @author FUJINGRUN
 *
 */
public class CmmContextListener implements ServletContextListener {

	private static final Logger logger = LoggerFactory.getLogger(CmmContextListener.class);

	private Pool<Jedis> jedisPool;
	
	@Override
	public void contextInitialized(ServletContextEvent event) {
		logger.info("=============应用程序启动===============");
		initRedisCfgByTillFileUpload();
		LogUtils.initPattern();
	}

	@Override
	public void contextDestroyed(ServletContextEvent sce) {
		try {
			ThreadPoolUtils.destory();
		} catch (Exception e) {
			logger.error("=============线程池停止失败===============", e);
		}
		
		if(null != jedisPool){
			jedisPool.destroy();
		}
		
		logger.info("=============应用程序停止===============");
	}
	
	/**
	 * 初始化缓存配置-用于文件上传
	 */
	private void initRedisCfgByTillFileUpload() {
		try {
			String maxTotal = PropertiesCacheUtils.getProperty("redis.redis.properties.jedis.max.total");
			String maxIdle = PropertiesCacheUtils.getProperty("redis.redis.properties.jedis.max.idle");
			String maxWaitMillis = PropertiesCacheUtils.getProperty("redis.redis.properties.jedis.max.idle");
			String testOnBorrow = PropertiesCacheUtils.getProperty("redis.redis.properties.jedis.test.on.borrow");
			JedisPoolConfig poolConfig = new JedisPoolConfig();
			poolConfig.setMaxTotal(Integer.valueOf(maxTotal));
			poolConfig.setMaxIdle(Integer.valueOf(maxIdle));
			poolConfig.setMaxWaitMillis(Long.valueOf(maxWaitMillis));
			poolConfig.setTestOnBorrow(Boolean.valueOf(testOnBorrow));

			String redisSentinel = PropertiesCacheUtils.getProperty("redis.redis.properties.jedis.jedispool.ip");
			Set<String> sentinels = new HashSet<String>();
			if (StringUtils.isNotEmpty(redisSentinel)) {
				sentinels.addAll(Arrays.asList(redisSentinel.split(",")));
			}

			String redisMasterName = PropertiesCacheUtils.getProperty("redis.redis.properties.jedis.master.name");
			jedisPool = new JedisSentinelPool(redisMasterName, sentinels, poolConfig, Protocol.DEFAULT_TIMEOUT, null,
					Protocol.DEFAULT_DATABASE);

			RedisUtils.init(jedisPool);
		} catch (Exception e) {
			BaseLogUtils.error(logger, "initRedisCfgByTillFileUpload", "初始化缓存配置-错误!", e);
		}
	}

}
